<template>
  <page-header-wrapper :title="false">
    <a-card title="订单详情">
      <a-descriptions bordered size="small">
        <a-descriptions-item label="订单" :span="3"> {{ info?.id }} </a-descriptions-item>
        <a-descriptions-item label="创建人" :span="3"> {{ info?.operator }} </a-descriptions-item>
        <a-descriptions-item label="创建日期" :span="3"> {{ info?.createTime }} </a-descriptions-item>
        <a-descriptions-item label="预计上账" :span="3"> {{ info?.accountEntry }} </a-descriptions-item>
        <a-descriptions-item label="金额" :span="3"> {{ info?.insAmount }} </a-descriptions-item>
        <a-descriptions-item label="类型" :span="3">
          {{ info?.accountType == '0' ? '待上账' : '已上账' }}
        </a-descriptions-item>
        <a-descriptions-item label="审核状态" :span="3">
          {{ info?.checkStatus === '1' ? '已审核' : '未审核' }}
        </a-descriptions-item>
        <a-descriptions-item label="审核人" :span="3" v-if="info?.checkStatus == '1' "> {{ info?.checkerName }} </a-descriptions-item>
        <a-descriptions-item label="备注" :span="3"> {{ info?.memo }} </a-descriptions-item>
        <a-descriptions-item label="操作" :span="3">
          <div style="display: flex">
            <!-- <a-button type="primary" style="margin:0px 5px" @click="handlePrice">上账</a-button>
            <a-button type="primary" style="margin:0px 5px" @click="handleEdit">编辑订单</a-button>
            -->
            <a-button type="danger" style="margin-right:5px" v-if="info?.checkStatus === '0' && info?.accountType !== '0'" @click="setCX(info)">撤销订单</a-button>
            <a-button type="primary" style="margin: 0px 5px" v-if="info?.checkStatus === '0'" @click="handleCheckPur()">审核</a-button
            >
            <a-button
              type="success"
              v-if="info?.checkStatus === '1'"
              style="margin: 0px 5px"
              @click="handleUnCheckPur()"
            >反审核</a-button
            >
          </div>
        </a-descriptions-item>
      </a-descriptions>
    </a-card>
    <a-card title="保价详情" style="margin-top: 24px">
      <template #extra>
        <a-tooltip>
          <template #title> 数据导出</template>
          <a-button type="primary" icon="database" @click="handleExpert(queryParam)"></a-button>
        </a-tooltip>
      </template>
      <div class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="48">
            <a-col :md="6" :sm="8">
              <a-form-item label="筛选">
                <a-input v-model="queryParam.keyword" placeholder="请输入筛选" />
              </a-form-item>
            </a-col>
            <a-col :md="(!advanced && 8) || 24" :sm="24">
              <span
                class="table-page-search-submitButtons"
                :style="(advanced && { float: 'right', overflow: 'hidden' }) || {}"
              >
                <a-button type="primary" :loading="loading" @click="handleSearch(queryParam)">查询</a-button>
                <a-button style="margin-left: 8px" @click="() => (queryParam = {})">重置</a-button>
                <!-- <a @click="toggleAdvanced" style="margin-left: 8px">
                  {{ advanced ? '收起' : '展开' }}
                  <a-icon :type="advanced ? 'up' : 'down'"/>
                </a> -->
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>

      <!-- <div class="table-operator">
        <a-button icon="cloud-upload">导出</a-button>
      </div> -->

      <a-table size="default" :loading="loading" rowKey="key" :columns="columns" :data-source="loadData">
        <span slot="serial" slot-scope="text, record, index">
          {{ index + 1 }}
        </span>
        <span slot="action" slot-scope="text, record">
          <template>
            <a-tag color="#428bca" @click="handleGoodsDetail(record)">详情</a-tag>
          </template>
        </span>
      </a-table>
    </a-card>
    <price-form
      ref="priceModal"
      :visible="priceVisible"
      :loading="priceLoading"
      :model="priceMdll"
      @cancel="handlePriceCancel"
      @ok="handlePriceOk"
    />
    <edit-form
      ref="editModal"
      :visible="editVisible"
      :loading="editLoading"
      :model="editMdll"
      @cancel="handleEditCancel"
      @ok="handleEditOk"
    />
  </page-header-wrapper>
</template>

<script>
import PriceForm from './PriceForm'
import EditForm from './EditForm'
import {
  getInsuredUsingGET,
  getInsDetailListUsingPOST,
  InsuredUnCheckPurUsingPOST,
  InsuredCheckPurUsingPOST,
  revokeInsuredUsingPOST,
  exportInsDetailUsingPOST
} from '@/api/api/caigouguanli.ts'
export default {
  name: 'ProtectPriceRecordDetail',
  components: {
    PriceForm,
    EditForm,
  },
  data() {
    return {
      info: {},
      queryParam: {
        pageNo: 1,
        pageSize: 10,
        queryCondition: '',
        status: '',
      },
      advanced: false,
      priceMdll: null,
      editMdll: null,
      priceVisible: false,
      editVisible: false,
      priceLoading: false,
      editLoading: false,
      loading: false,
      columns: [
        {
          title: '入库日期',
          dataIndex: 'inDate',
        },
        {
          title: '保价日期',
          dataIndex: 'orderDate',
        },
        {
          title: '商品',
          dataIndex: 'goodsName',
        },
        {
          title: '串码',
          dataIndex: 'phoneCode',
        },
        {
          title: '调整金额(元)',
          dataIndex: 'insAmount',
        },
        {
          title: '供应商',
          dataIndex: 'supplyName',
        },
        {
          title: '保价供应商',
          dataIndex: 'insSupplyName',
        },
        {
          title: '操作',
          dataIndex: 'action',
          width: '150px',
          scopedSlots: { customRender: 'action' },
        },
      ],
      loadData: [],
      pagination: {},
    }
  },
  mounted() {
    this.getDetail()
    this.handleSearch(this.queryParam)
  },
  methods: {
    handleExpert(params){
      exportInsDetailUsingPOST({...params, orderId: this.$route.params.id }).then((res) => {
          const blob = new Blob([res], {
            type: 'application/vnd.ms-excel;charset=utf-8',
          })
          const filename = '保价记录详情列表' + '.xlsx'
          // 将blob对象转为一个URL
          var blobURL = window.URL.createObjectURL(blob)
          // 创建一个a标签
          var tempLink = document.createElement('a')
          // 隐藏a标签
          tempLink.style.display = 'none'
          // 设置a标签的href属性为blob对象转化的URL
          tempLink.href = blobURL
          // 给a标签添加下载属性
          tempLink.setAttribute('download', filename)
          if (typeof tempLink.download === 'undefined') {
            tempLink.setAttribute('target', '_blank')
          }
          // 将a标签添加到body当中
          document.body.appendChild(tempLink)
          // 启动下载
          tempLink.click()
          // 下载完毕删除a标签
          document.body.removeChild(tempLink)
          window.URL.revokeObjectURL(blobURL)
          this.$message.success('导出成功~')
        })  
    },
    setCX(info) {
      const that = this
      that.$confirm({
        title: '撤销订单',
        content: '你确定要撤销该订单吗？',
        okText: '确认',
        okType: 'danger',
        cancelText: '取消',
        onOk() {
          revokeInsuredUsingPOST({ id: info.id })
            .then(() => {
              that.$router.back()
              that.$message.success('操作成功')
            })
            .catch((error) => {
              that.$message.error(((error.response || {}).data || {}).msg || '请求出现错误')
            })
        },
      })
    },
    getDetail() {
      getInsuredUsingGET({ id: this.$route.params.id })
        .then((res) => {
          this.info = res.data
        })
        .catch(() => {
          this.$message.error('获取详情失败,请联系管理员')
        })
    },
    handleSearch(params) {
      this.loading = true
      getInsDetailListUsingPOST({ ...params, orderId: this.$route.params.id })
        .then((res) => {
          this.loadData = res.data.list
          this.loading = false
          this.queryParam.pageNo = this.pagination.current
          this.pagination = { ...this.pagination, total: Number(res.data.total) }
        })
        .catch(() => {
          this.loading = false
          this.$message.error('获取保价详情失败,请联系管理员')
        })
    },
    handleTableChange(pagination, filters, sorter) {
      const pager = { ...this.pagination }
      pager.current = pagination.current
 pager.pageSize = pagination.pageSize
      this.pagination = pager
      this.handleSearch({
        sortField: sorter.field,
        sortOrder: sorter.order,
        ...filters,
        pageNo: pagination.current,
        pageSize: pagination.pageSize,
        queryCondition: this.queryParam.queryCondition,
        status: this.queryParam.status,
        date: this.queryParam.date,
      })
    },
    handleEdit() {
      this.editMdll = { id: 1 }
      this.editVisible = true
    },
    handleEditOk() {
      this.editVisible = false
      this.editLoading = true
      setTimeout(() => {
        this.editLoading = false
      }, 1000)
      this.$message.success('操作成功')
    },
    handleEditCancel() {
      this.editVisible = false
      const form = this.$refs.editModal.form
      form.resetFields() // 清理表单数据（可不做）
    },
    handlePrice() {
      this.priceMdll = { id: 1 }
      this.priceVisible = true
    },
    handlePriceOk() {
      this.priceVisible = false
      this.priceLoading = true
      setTimeout(() => {
        this.priceLoading = false
      }, 1000)
      this.$message.success('操作成功')
    },
    handlePriceCancel() {
      this.priceVisible = false
      const form = this.$refs.priceModal.form
      form.resetFields() // 清理表单数据（可不做）
    },
    handleChange(record) {
      this.$router.push({ path: `/purchasing/ProtectPriceRecord/edit/${record.id}` })
    },
    handleGoodsDetail(record) {
      this.$router.push({ path: `/goods/name/${record.inventoryId}` })
    },
    handleCheckPur() {
      const that = this
      that.$confirm({
        title: '审核通过',
        content: '你确定要审核通过该订单吗？',
        okText: '确认',
        okType: 'danger',
        cancelText: '取消',
        onOk() {
          InsuredCheckPurUsingPOST({ id: that.$route.params.id })
            .then(() => {
              that.handleSearch(that.queryParam)
              that.getDetail()
              that.$message.success('操作成功')
            })
            .catch((error) => {
              that.$message.error(((error.response || {}).data || {}).msg || '请求出现错误')
            })
        },
      })
    },
    handleUnCheckPur() {
      const that = this
      that.$confirm({
        title: '反审核',
        content: '你确定要反审核该订单吗？',
        okText: '确认',
        okType: 'danger',
        cancelText: '取消',
        onOk() {
          InsuredUnCheckPurUsingPOST({ id: that.$route.params.id })
            .then(() => {
              that.handleSearch(that.queryParam)
              that.getDetail()
              that.$message.success('操作成功')
            })
            .catch((error) => {
              that.$message.error(((error.response || {}).data || {}).msg || '请求出现错误')
            })
        },
      })
    },
  },
}
</script>
